/**
 * @file OrderHistoryPage.jsx
 * @description 用户订单历史页面组件。
 */
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchUserOrders } from '../store/orderSlice';
import { FaShoppingBag, FaInfoCircle, FaCalendarAlt, FaTags, FaSpinner } from 'react-icons/fa'; // 导入图标
import toast from 'react-hot-toast';

const OrderHistoryPage = () => {
  const dispatch = useDispatch();
  const { user } = useSelector((state) => state.auth);
  const { orders, isLoading, error } = useSelector((state) => state.orders);

  useEffect(() => {
    if (user && user.id) {
      dispatch(fetchUserOrders(user.id));
    } else {
      // 如果用户未登录或用户ID不存在，可以提示或重定向
      // ProtectedRoute 应该已经处理了未登录的情况
      toast.error("无法加载订单，用户未登录或信息不完整。");
    }
  }, [dispatch, user]);

  if (isLoading) {
    return (
      <div className="container my-5 py-5 text-center">
        <FaSpinner className="fa-spin fa-3x text-primary" />
        <p className="mt-3">正在加载您的订单...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container my-5 py-5 text-center">
        <FaInfoCircle size={50} className="text-danger mb-3" />
        <h4>加载订单时出错</h4>
        <p className="text-muted">{error}</p>
        <Link to="/profile" className="btn btn-outline-secondary mt-3">返回用户中心</Link>
      </div>
    );
  }

  if (!orders || orders.length === 0) {
    return (
      <div className="container my-5 py-5 text-center">
        <FaShoppingBag size={50} className="text-muted mb-3" />
        <h4>您还没有任何订单记录。</h4>
        <p className="text-muted">立即开始购物，发现心仪的商品吧！</p>
        <Link to="/products" className="btn btn-primary mt-3">去购物</Link>
      </div>
    );
  }

  return (
    <div className="container my-5 py-5">
      <div className="row mb-4">
        <div className="col-12 text-center">
          <h1 className="display-5 fw-bold">我的订单</h1>
          <hr />
        </div>
      </div>

      {orders.map((order) => (
        <div key={order.orderId} className="card shadow-sm mb-4">
          <div className="card-header bg-light d-flex justify-content-between align-items-center">
            <div>
              <FaCalendarAlt className="me-2 text-muted" />
              <strong>订单日期:</strong> {new Date(order.date).toLocaleDateString('zh-CN')} {/* 本地化日期显示 */}
            </div>
            <div>
              <FaTags className="me-2 text-muted" />
              <strong>订单号:</strong> {order.orderId}
            </div>
          </div>
          <div className="card-body">
            <h5 className="card-title">订单状态: <span className={`badge bg-${order.status === '处理中' ? 'warning' : 'success'}`}>{order.status}</span></h5>
            <div className="mb-3">
              <h6>商品列表:</h6>
              <ul className="list-group list-group-flush">
                {order.items.map((item) => (
                  <li key={`<span class="math-inline">\{order\.orderId\}\-</span>{item.id}`} className="list-group-item d-flex justify-content-between align-items-center">
                    <div>
                      <Link to={`/product/${item.id}`} className="fw-bold text-decoration-none">{item.title}</Link>
                      <small className="d-block text-muted">单价: ${item.price.toFixed(2)} x {item.qty}</small>
                    </div>
                    <span>${(item.price * item.qty).toFixed(2)}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div className="row border-top pt-3 mt-3">
              <div className="col-md-6">
                <h6>配送地址:</h6>
                <p className="mb-1">{order.shippingAddress.fullName}</p>
                <p className="mb-1">{order.shippingAddress.address}, {order.shippingAddress.address2 || ''}</p>
                <p className="mb-1">{order.shippingAddress.state}, {order.shippingAddress.country}, {order.shippingAddress.zip}</p>
                <p className="mb-0"><small>邮箱: {order.shippingAddress.email || '未提供'}</small></p>
              </div>
              <div className="col-md-6 text-md-end">
                <p className="mb-1">商品小计: ${order.subtotal.toFixed(2)}</p>
                <p className="mb-1">运费: ${order.shipping.toFixed(2)}</p>
                <h5 className="mb-0 fw-bold">订单总计: ${order.totalAmount.toFixed(2)}</h5>
                <p className="mb-0 small text-muted">支付方式: {order.paymentMethod}</p>
              </div>
            </div>
          </div>
          {/* <div className="card-footer text-muted">
            可以添加例如 "再次购买" 或 "查看发票" 等按钮
          </div> */}
        </div>
      ))}
       <div className="text-center mt-4">
            <Link to="/profile" className="btn btn-outline-secondary">
                返回用户中心
            </Link>
        </div>
    </div>
  );
};

export default OrderHistoryPage;